package com.example.springboot.service;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.common.FosterOrderEnum;
import com.example.springboot.common.PetEnum;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.FosterOrderDao;
import com.example.springboot.dao.PetDao;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.FosterOrder;
import com.example.springboot.entity.Pet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class FosterOrderService {
    @Resource
    FosterOrderDao fosterOrderDao;
    @Resource
    PetDao  petDao;

    public List<FosterOrder> selectAll() {
        return fosterOrderDao.selectAll(null);
    }

    public void updateById(FosterOrder fosterOrder) {
        fosterOrderDao.updateById(fosterOrder);
    }

    public PageInfo<FosterOrder> selectPage(FosterOrder fosterOrder, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<FosterOrder> fosterOrderList = fosterOrderDao.selectAll(fosterOrder);
        return PageInfo.of(fosterOrderList);
    }

    public void saveFosterOrder(FosterOrder fosterOrder) {
        Account account=JwtTokenUtils.getCurrentUser();
        fosterOrder.setUserId( account.getId());
        fosterOrder.setTime(DateUtil.now());
        fosterOrder.setState(FosterOrderEnum.ALREADY_BOOKED.state);
        Pet pet=petDao.selectById(fosterOrder.getPetId());
        pet.setState(PetEnum.ALREADY_BOOKED.state);
        petDao.updateById(pet);
        fosterOrderDao.insertFosterOrder(fosterOrder);

    }

    public void deleteById(Integer id) {
        fosterOrderDao.deleteById(id);
    }


    public void updateState(FosterOrder fosterOrder) {
        Pet pet=    petDao.selectById(fosterOrder.getPetId());
        if (fosterOrder.getState().equals(FosterOrderEnum.ALREADY_BOOKED.state)){
            fosterOrder.setState(FosterOrderEnum.CHECK_IN.state);
            pet.setState(PetEnum.CHECK_IN.state);
        }
        else {
            fosterOrder.setState(FosterOrderEnum.OVER.state);
            pet.setState(PetEnum.NO_FOSTER.state);
        }
        petDao.updateById(pet);
        fosterOrderDao.updateById(fosterOrder);
    }
}